import React, { Component } from 'react';
import { DeviceInfo, StyleSheet, View, Button } from 'react-native';
import { WebView } from 'react-native-webview';
import BackPressComponent from "../../global/components/BackPressComponent";
import CommonViewFactory from "../../global/util/CommonViewFactory";
import Share from 'react-native-share';

type
Props = {};

export default class WebViewScreen extends Component<Props> {
  static navigationOptions = ({ navigation }) => {//动态设置title
    const { params } = navigation.state;
    return {
      headerTitle: params && params.title,
      headerRight: CommonViewFactory.getShareButton(() => {
        Share.open({
          url: params.url
        })
          .then((res) => { console.log(res) })
          .catch((err) => { err && console.log(err); });
      }),
    };
  };
  constructor(props) {
    super(props);
    this.params = this.props.navigation.state.params;
    const { title, url } = this.params;
    this.state = {
      title: title,
      url: url,
      canGoBack: false,
    };
    this.backPress = new BackPressComponent({ backPress: () => this.onBackPress() });
  }
  componentDidMount() {
    this.backPress.componentDidMount();
  }

  componentWillUnmount() {
    this.backPress.componentWillUnmount();
  }

  onBackPress() {
    this.onBack();
    return true;
  }

  onBack() {
    if (this.state.canGoBack) {
      this.webView.goBack();
    } else {
      this.props.navigation.goBack();
    }
  }

  onNavigationStateChange(navState) {
    this.setState({
      canGoBack: navState.canGoBack,
      url: navState.url,
    })
  }

  render() {
    return (
      <View style={{ overflow: 'hidden', flex: 1 }}>
        <WebView
          ref={webView => this.webView = webView}
          startInLoadingState={true}
          onNavigationStateChange={e => this.onNavigationStateChange(e)}
          source={{ uri: this.state.url }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: DeviceInfo.isIPhoneX_deprecated ? 30 : 0
  },
});
